package com.iwa.shop.annotation.support;

import com.iwa.common.constants.CommonConstants;
import com.iwa.common.context.FilterContextHandler;
import com.iwa.common.dto.UserToken;
import com.iwa.common.utils.JwtUtils;
import com.iwa.shop.annotation.LoginAdmin;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


public class LoginAdminHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginAdmin.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {


        String token = request.getHeader(CommonConstants.CONTEXT_TOKEN);
        if (token == null || token.isEmpty()) {
            return null;
        }
        UserToken userToken = JwtUtils.getInfoFromToken(token);
        return Integer.valueOf(userToken.getUserId()) ;
    }
}
